package cz.data.domain.system.service.impl;

import cz.data.common.mybatis.BaseServiceImpl;
import cz.data.common.exception.DataException;
import cz.data.domain.system.dao.RoleMenuDao;
import cz.data.domain.system.model.dto.MenuDto;
import cz.data.domain.system.model.entity.MenuEntity;
import cz.data.domain.system.dao.MenuDao;
import cz.data.domain.system.mapstruct.MenuMapper;
import cz.data.domain.system.model.entity.RoleMenuEntity;
import cz.data.domain.system.service.MenuService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MenuServiceImpl extends BaseServiceImpl<MenuDao, MenuEntity> implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleMenuDao roleMenuDao;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MenuEntity saveMenu(MenuDto menuDto) {
        MenuEntity menu = menuMapper.toEntity(menuDto);
        menuDao.insert(menu);
        return menu;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MenuEntity updateMenu(MenuDto menuDto) {
        MenuEntity menu = menuMapper.toEntity(menuDto);
        menuDao.updateById(menu);
        return menu;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMenuById(String id) {
        long n = menuDao.selectCount(Wrappers.<MenuEntity>lambdaQuery().eq(MenuEntity::getParentId, id));
        if(n > 0){
            throw new DataException("该菜单下存在子菜单数据");
        }
        menuDao.deleteById(id);
    }

    @Transactional
    @Override
    public void deleteMenuByTreeId(String id) {
        deleteTreeNode(id);
    }

    private void deleteTreeNode(String id) {
        List<MenuEntity> subNode = menuDao.selectList(Wrappers.<MenuEntity>lambdaQuery().eq(MenuEntity::getParentId, id));
        if (CollectionUtils.isNotEmpty(subNode)) {
            for (MenuEntity menu : subNode) {
                deleteTreeNode(menu.getId());
            }
        }
        roleMenuDao.delete(Wrappers.<RoleMenuEntity>lambdaQuery().eq(RoleMenuEntity::getMenuId, id));
        menuDao.deleteById(id);
    }
}
